package com.polito.mad.bikeponyapp.fragments;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.polito.mad.bikeponyapp.R;
import com.polito.mad.bikeponyapp.persistence.Question;
import com.polito.mad.bikeponyapp.persistence.QuestionsRepository;
import com.polito.mad.bikeponyapp.persistence.RepositoryHolder;
import com.polito.mad.bikeponyapp.util.SimpleAnimationListener;

public class FeedbackFragment extends Fragment {
	
	
	private QuestionsRepository questionRepository;
	
	private OnFeedbackSaveListener mFeedbackSaveListner;
	
	private Context context;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getActivity().getActionBar().setDisplayShowTitleEnabled(true);
	    getActivity().setTitle("Delivery feedback");
	    
	    context = getActivity();
	}
	
	@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        questionRepository = ((RepositoryHolder)getActivity().getApplication()).getQuestionsRepository();
        try {
        	mFeedbackSaveListner = (OnFeedbackSaveListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnFeedbackSaveListener");
        }
    }
	
	@Override
	public void onStart() {
		super.onStart();
		
		showToolbar();
	}
	
	// Container Activity must implement this interface
    public interface OnFeedbackSaveListener {
        public void onFeedbackSave(String sData);
    }
    
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		
	    View myView = inflater.inflate(R.layout.feedback_fragment_layout, container, false);
		Button clearButton = (Button) myView.findViewById(R.id.clearFeedbackButton);
		clearButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				clearFeedbackSelection();
			}
		});
		
		Button saveButton = (Button) myView.findViewById(R.id.saveFeedbackButton);
		saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveFeedback();
			}
		});
	    return myView;
	}
	
	private void clearFeedbackSelection()
	{
		LinearLayout formLayout = (LinearLayout)getView().findViewById(R.id.feedback_question_layout);
		
		for(int i = 0; i< formLayout.getChildCount(); i++)
		{
			RatingBar rB = null;
			try
			{
				rB= (RatingBar) formLayout.getChildAt(i);
			}
			catch(ClassCastException excp)
			{
				continue;				
			}
			if(rB != null)
			{
				rB.setRating(0f);
				//rB.clearAnimation();
			}
		}
	}
	
	private void saveFeedback()
	{
		String sJsonData = "[";
		LinearLayout formLayout = (LinearLayout)getView().findViewById(R.id.feedback_question_layout);
		
		for(int i = 0; i< formLayout.getChildCount(); i++)
		{
			RatingBar rB = null;
			if(formLayout.getChildAt(i) instanceof RatingBar)
			{
				try
				{
					rB = (RatingBar) formLayout.getChildAt(i);
				}
				catch(ClassCastException excp)
				{
					continue;				
				}
				
				if(rB != null )
				{	
					rB.getRating();
					Long questionId = (Long)rB.getTag();
					
					sJsonData += questionId.toString() + "-" + String.valueOf(Math.round(rB.getRating())) + ","; 
				}
			}
		}
		
		sJsonData += "]";
		
		mFeedbackSaveListner.onFeedbackSave(sJsonData) ;
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
	
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	public void showToolbar()
    {
            //fadeListViewBackground(getResources().getColor(R.color.delivery_list_normal_mode_background),getResources().getColor(R.color.delivery_list_edit_mode_background));
		RelativeLayout layout = (RelativeLayout)getActivity().findViewById(R.id.feedback_toolbar_layout);
        layout.setVisibility(View.VISIBLE);
        Animation bump = AnimationUtils.loadAnimation(context, R.anim.bump_out_view);
        layout.setAnimation(bump);
        bump.setAnimationListener(new SimpleAnimationListener(){
        	 @Override
             public void onAnimationEnd(Animation animation) {
        		 getView().invalidate();
             }
        });
        bump.setFillAfter(true);
        bump.start();
    }
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		LinearLayout formLayout = (LinearLayout)getView().findViewById(R.id.feedback_question_layout);
	    
	    if(formLayout != null)
	    {
		    formLayout.removeAllViews();
		    formLayout.setPadding(10, 10, 5, 10);
		    		    
		    LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.SCROLLBAR_POSITION_DEFAULT                    
                    );
		    
		    		    
		    List<Question> questionList =  questionRepository.getAll();
		    if(questionList.size() == 0)
		    {
		    	//it should not happen...
		    	TextView tv=new TextView(getActivity());
	    		tv.setLayoutParams(lparams);
	    		tv.setText(getString(R.string.no_question_found));
	    		formLayout.addView(tv);
		    	
		    }
		    for(Question question: questionList)
		    {
		    	TextView tv=new TextView(getActivity());
	    		tv.setLayoutParams(lparams);
	    		tv.setText(question.getText());
	    		tv.setPadding(0, 5, 0, 5);

	    		formLayout.addView(tv);
	    		
	    		RatingBar rB = new RatingBar(getActivity());
	    		rB.setLayoutParams(lparams);
	    		rB.setStepSize(1);
	    		rB.setNumStars(5);
	    		rB.setTag(question.getId());
	    		rB.setPadding(0, 5, 0, 5);
	    		formLayout.addView(rB);
	    		
	    		ImageView divider = new ImageView(context);
			    LinearLayout.LayoutParams lp = 
			        new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 5);
			    lp.setMargins(10, 10, 10, 10);
			    divider.setLayoutParams(lp);
			    divider.setBackgroundColor(Color.GRAY);
			    formLayout.addView(divider);
			    
		    }
		    
	    }
		super.onViewCreated(view, savedInstanceState);
	}

}
